﻿function Login() {
    var self = this;
    this.name = ko.observable().extend({ required: "Please enter login name" });
    this.password = ko.observable().extend({ required: "Please enter password" });
    this.returnUrl = ko.observable();
    this.errors = ko.observableArray();
    this.errorMessage = ko.computed({
        read: function () {
            var html = '';
            if (this.errors().length > 0)
                html += this.errors()[0];
            if (this.errors().length > 1) {
                html += "<ul>"
                for (var idx = 1; idx < this.errors().length; idx++)
                    html += "<li>" + this.errors()[idx] + "</li>";
                html += "</ul>";
            }
            return html;
        },
        write: function (value) {
            this.errors.removeAll();
            this.errors.push(value);
        },
        owner: this
    });

    this.hasError = ko.computed(function () {
        return this.name.hasError() || this.password.hasError();
    }, this);

    this.setError = function () {
        if (this.hasError()) {
            this.errorMessage("Please correct the following errors:");
            if (this.name.hasError())
                this.errors.push(this.name.validationMessage());
            if (this.password.hasError())
                this.errors.push(this.password.validationMessage());
        } else {
            this.clearError();
        }
    }

    this.clearError = function () {
        this.errors.removeAll();
    }

    this.login = function () {
        if (this.hasError()) {
            this.setError();
        } else {
            var url = appPath + 'Admin/Login';
            var input = {
                name: this.name(),
                password: this.password()
            };
            $.post(url, input, function (data) {
                if (data.Result) {
                    window.location = self.returnUrl();
                } else {
                    self.errorMessage(data.Message);
                    if (data.Errors) {
                        for (var idx = 0; idx < data.Errors.length; idx++)
                            self.errors.push(data.Errors[idx]);
                    }
                }
            });
        }
    }
}